# -*- coding: utf-8 -*-
from flask import Blueprint, request, jsonify, make_response, redirect, g

from common.libs.Helper import ops_render
from common.libs.Restful import Restful
from common.libs.UrlManager import UrlManager
from common.libs.user.UserService import UserService
from common.models.user import User
from application import app, db

import json

route_user = Blueprint('user_page', __name__)


@route_user.route("/login", methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return ops_render('user/login.html')
    resp = {'code':200, 'msg':'登录成功', 'data':{}}
    req = request.values
    login_name = req['login_name'] if 'login_name' in req else ''
    login_pwd = req['login_pwd'] if 'login_pwd' in req else ''
    if login_name is None or len(login_name) < 1:
        return Restful.param_error(msg='请输入正确的登录名')
    if login_pwd is None or len(login_pwd) < 1:
        return Restful.param_error(msg='请输入正确的密码')
    user = User.query.filter_by(login_name=login_name).first()
    if not user:
        return Restful.param_error(msg='请输入正确的登录名和密码')

    # 用户密码加密算法
    if user.login_pwd != UserService.genePwd(pwd=login_pwd, salt=user.login_salt):
        return Restful.param_error(msg='请输入正确的登录名和密码')

    resp['data'] = {
        'login_name': login_name
    }

    response = Restful.success()
    response.set_cookie(app.config['AUTH_COOKIE_NAME'], '%s#%s'%(UserService.geneAuthCode(user), user.uid), 60*60*24)
    return response


@route_user.route("/edit", methods=['POST', 'GET'])
def edit():
    if request.method == 'GET':
        return ops_render("user/edit.html")
    else:
        req = request.values
        nickname = req.get('nickname')
        email = req.get('email')
        if not nickname or len(nickname) < 2:
            return Restful.param_error(msg='请输入正确的用户名')
        if not email or len(email) < 2:
            return Restful.param_error(msg='请输入正确的邮箱地址')
        user = g.current_user
        user.nickname = nickname
        user.email = email
        db.session.commit()
        return Restful.success()

@route_user.route("/resetpwd", methods=['POST', 'GET'])
def resetPwd():
    if request.method == 'GET':
        return ops_render("user/reset_pwd.html")
    old_password = request.form.get('old_password')
    new_password = request.form.get('new_password')
    if not old_password or len(old_password)<6 or len(old_password)>20:
        return Restful.param_error(msg='请输入正确的密码格式')
    if not new_password or len(new_password)<6 or len(new_password)>20:
        return Restful.param_error(msg='请输入正确的密码格式')
    if old_password != new_password:
        return Restful.param_error(msg='两次输入的密码不一致')
    user = g.current_user
    user.login_pwd = UserService.genePwd(old_password, user.login_salt)
    db.session.commit()
    response = Restful.success()
    response.set_cookie(app.config['AUTH_COOKIE_NAME'], '%s#%s' % (UserService.geneAuthCode(user), user.uid), 60*60*24)
    return response



@route_user.route('/logout')
def loginout():
    response = make_response(redirect(UrlManager.buildUrl('/user/login')))
    response.delete_cookie(app.config['AUTH_COOKIE_NAME'])
    return response